/*
 * main.c
 *
 *  Created on: Nov 28, 2010
 *      Author: cumeo89
 */

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <glib.h>
#include <glib/gstdio.h>
#include "gui.h"
#include "visual.h"
#include "lcstr.h"
#include "lcsfile.h"
#include "textgen.h"
#include <time.h>
#include "benmark.h"

#define MODE_RUN
//#define MODE_BENMARK
//#define MODE_TEST

int test() {
	int K = 3;
	const gchar *strings[] = {
			"xabxa",
			"abxbx",
			"abcbx",
			NULL
	};

	VisualizerData data;
	data.dot = "dot";
	data.edgeLabelType = EDGE_LABEL_TYPE_SUBSTRING;
	data.counter = 0;
	data.dir = g_build_path(G_DIR_SEPARATOR_S, g_get_tmp_dir(), "cs-suffix-tree", NULL);
	g_mkdir(data.dir, 0777);

	printf("Generating images into %s... ", data.dir);
	SuffixTree *tree = t_new_callback(strings, visualize, &data);
//	visualize(tree, &data, 0, 0);
	printf("Done.\n");

	CommonString *cs = find_lcstr_tree(strings, tree);
	int k;
	for (k = 0; k < K-1; k++) {
		gchar *atLeast = (k < K-2 ? "at least " : "");
		printf("Longest in %s%d strings: %s\n", atLeast, k+2, cs_get_substring(&cs[k]));
	}

	g_free(data.dir);
	t_free(tree);
	cs_free(cs, K);
	return 0;
}

int doGenerate(int argc, char **argv) {
	long fileSize;
	int fileCount;
	char *filePattern = argv[4];
	if (sscanf(argv[2], "%ld", &fileSize) != 1) {
		printf("Wrong file size.");
		return 1;
	}
	if (sscanf(argv[3], "%d", &fileCount) != 1) {
		printf("Wrong file count.");
		return 2;
	}
	return generate(fileSize, fileCount, filePattern);
}

int run(int argc, char **argv) {
	clock_t start = clock();
	printf("Running...\n");
	fflush(stdout);
	int ret;
	if (argc >= 2 && strcmp(argv[1], "-c") == 0) {
		ret = lcsfile_run((const char**)&argv[2]);
	} else if (argc >= 2 && strcmp(argv[1], "-g") == 0) {
		ret = doGenerate(argc, argv);
	} else {
		ret = gui_run();
	}
	clock_t stop = clock();
	double elapsed = ((double) (stop - start)) / CLOCKS_PER_SEC;
	printf("Done (%.2fs).\n", elapsed);
	return ret;
}

int main(int argc, char **argv) {
	#ifdef MODE_RUN
	return run(argc, argv);
	#endif

	#ifdef MODE_BENMARK
	return benmark(1*1024*1024, 1024);
	#endif

	#ifdef MODE_TEST
	return test();
	#endif
}
